import { ref, computed } from 'vue';
import { defineStore } from 'pinia';

export interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

export const useTodoStore = defineStore('todo', () => {
  const todos = ref<Todo[]>([]);
  const filter = ref<'all' | 'active' | 'completed'>('all');
  let nextId = 1;

  function addTodo(text: string) {
    todos.value.push({ id: nextId++, text, completed: false });
  }
  function removeTodo(id: number) {
    todos.value = todos.value.filter((t) => t.id !== id);
  }
  function clearCompleted() {
    todos.value = todos.value.filter((t) => !t.completed);
  }
  function setFilter(f: 'all' | 'active' | 'completed') {
    filter.value = f;
  }

  const filteredTodos = computed(() => {
    if (filter.value === 'active') return todos.value.filter((t) => !t.completed);
    if (filter.value === 'completed') return todos.value.filter((t) => t.completed);
    return todos.value;
  });
  const remaining = computed(() => todos.value.filter((t) => !t.completed).length);
  const completed = computed(() => todos.value.length - remaining.value);
  const allCompleted = computed(() => todos.value.some((t) => t.completed));

  return {
    todos,
    filter,
    addTodo,
    removeTodo,
    clearCompleted,
    setFilter,
    filteredTodos,
    remaining,
    completed,
    allCompleted,
  };
});
